package com.example.project.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.example.project.core.text.Convert;
import com.example.project.entity.Attachment;
import com.example.project.mapper.AttachmentMapper;
import com.example.project.service.AttachmentService;
import com.example.project.utils.DateUtils;

/**
 * 附件，存储系统中所有上传的文件信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-23
 */
@Service
public class AttachmentServiceImpl extends BaseServiceImpl implements AttachmentService {

	private static final Logger logger = LoggerFactory.getLogger(AttachmentService.class);

	@Autowired
	private AttachmentMapper attachmentMapper;

	/**
	 * 查询附件，存储系统中所有上传的文件信息
	 * 
	 * @param id 附件，存储系统中所有上传的文件信息主键
	 * @return 附件，存储系统中所有上传的文件信息
	 */
	@Override
	public Attachment selectAttachmentById(Long id) {
		return attachmentMapper.selectAttachmentById(id);
	}

	/**
	 * 查询附件，存储系统中所有上传的文件信息列表
	 * 
	 * @param attachments 附件，存储系统中所有上传的文件信息
	 * @return 附件，存储系统中所有上传的文件信息
	 */
	@Override
	public List<Attachment> selectAttachmentList(Attachment attachments) {
		return attachmentMapper.selectAttachmentList(attachments);
	}

	/**
	 * 新增附件，存储系统中所有上传的文件信息
	 * 
	 * @param attachments 附件，存储系统中所有上传的文件信息
	 * @return 结果
	 */
	@Override
	public Attachment insertAttachment(Attachment attachments) {
		attachments.setCreateTime(DateUtils.curLocalDateTime());
		attachmentMapper.insertAttachment(attachments);
		return attachments;
	}

	/**
	 * 修改附件，存储系统中所有上传的文件信息
	 * 
	 * @param attachments 附件，存储系统中所有上传的文件信息
	 * @return 结果
	 */
	@Override
	public int updateAttachment(Attachment attachments) {
		attachments.setUpdateTime(DateUtils.curLocalDateTime());
		return attachmentMapper.updateAttachment(attachments);
	}

	/**
	 * 批量删除附件，存储系统中所有上传的文件信息
	 * 
	 * @param ids 需要删除的附件，存储系统中所有上传的文件信息主键
	 * @return 结果
	 */
	@Override
	public int deleteAttachmentByIds(String ids) {
		return attachmentMapper.deleteAttachmentByIds(Convert.toStrArray(ids));
	}

	/**
	 * 删除附件，存储系统中所有上传的文件信息信息
	 * 
	 * @param id 附件，存储系统中所有上传的文件信息主键
	 * @return 结果
	 */
	@Override
	public int deleteAttachmentById(Long id) {
		return attachmentMapper.deleteAttachmentById(id);
	}

	/**
	 * 保存附件信息
	 * 
	 * @return
	 */
	@Override
	public List<Attachment> saveAttachments(Long issueId, String uploadedFilesJson) {
		List<Attachment> list = Lists.newArrayList();
		try {
			JSONArray filesArray = JSON.parseArray(uploadedFilesJson);
			for (int i = 0; i < filesArray.size(); i++) {
				JSONObject fileInfo = filesArray.getJSONObject(i);
				Attachment attachment = new Attachment();
				attachment.setContainerId(issueId);
				attachment.setContainerType("Issue");
				attachment.setFilename(fileInfo.getString("originalFilename"));
				attachment.setDiskFilename(fileInfo.getString("diskFilename"));
				attachment.setFilePath(fileInfo.getString("filename"));
				attachment.setFilesize(fileInfo.getLong("fileSize"));
				attachment.setContentType(getContentType(fileInfo.getString("filename")));
				attachment.setAuthorId(getUserId()); // 获取当前用户ID
				attachment.setCreateBy(getLoginName());

				attachment = insertAttachment(attachment);
				list.add(attachment);
			}
		} catch (Exception e) {
			System.err.println("保存附件信息失败: " + e.getMessage());
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 获取文件内容类型
	 */
	private String getContentType(String filename) {
		if (filename == null)
			return "application/octet-stream";
		if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
			return "image/jpeg";
		if (filename.endsWith(".png"))
			return "image/png";
		if (filename.endsWith(".gif"))
			return "image/gif";
		if (filename.endsWith(".pdf"))
			return "application/pdf";
		if (filename.endsWith(".doc") || filename.endsWith(".docx"))
			return "application/msword";
		if (filename.endsWith(".xls") || filename.endsWith(".xlsx"))
			return "application/vnd.ms-excel";
		if (filename.endsWith(".zip"))
			return "application/zip";
		if (filename.endsWith(".rar"))
			return "application/x-rar-compressed";
		return "application/octet-stream";
	}

	@Override
	public List<Attachment> queryAttachmentsListByIdAndType(Long containerId, String containerType) {
		// TODO Auto-generated method stub
		return attachmentMapper.queryAttachmentsListByIdAndType(containerId, containerType);
	}

	@Override
	public List<Attachment> selectAttachmentListByIds(List<Long> ids) {
		return attachmentMapper.selectAttachmentListByIds(ids);
	}

	/**
	 * 增加下载计数 类似Ruby中的@attachment.increment_download
	 */
	public void incrementDownloadCount(Attachment attachment) {
		if (attachment != null) {
			long currentCount = attachment.getDownloads() != null ? attachment.getDownloads() : 0;
			attachment.setDownloads(currentCount + 1);
			attachmentMapper.insertAttachment(attachment);
		}
	}

	/**
	 * 检查容器是否有附件 类似Ruby中的@container.respond_to?(:attachments)
	 */
	public boolean hasAttachment(String containerType) {
		if (containerType == null) {
			return false;
		}

		// 检查容器是否有附件关联
		return attachmentMapper.countByContainer(containerType) > 0;
	}

	/**
	 * 获取容器的附件列表 类似Ruby中的@container.attachments.to_a
	 */
	public List<Attachment> getContainerAttachment(String containerType) {
		if (containerType == null) {
			return List.of();
		}

		return attachmentMapper.findByContainerOrderByCreatedAtAsc(containerType);
	}

	@Override
	public Object findContainerById(Class<?> klass, Long objectId) {
		// TODO Auto-generated method stub
		return attachmentMapper.findContainerById(objectId);
	}

}
